package main

import (
	"strings"
	"fmt"
	"net/http"
	"io/ioutil"
	"io"
	"bytes"
	"os"
)

func main() {
	furl := "http://mtg.jflyfox.com/jflyfox/mtg/article_image/20160921_003022_47566.jpg"
	n, _ := getImg(furl)
	fmt.Println(n)
}

func getImg(url string) (n int64, err error) {

	path := strings.Split(url, "/")
	var name string
	if len(path) > 1 {
		name = path[len(path)-1]
	}
	fmt.Println(name)

	// file is exists
	flag, err := exists(name)
	if flag {
		fmt.Println(111)
		return
	}

	// if temp file exists , return sleep

	// create temp file （yyyyMMdd.tmp）

	// download file
	out, err := os.Create(name)
	defer out.Close()
	resp, err := http.Get(url)
	defer resp.Body.Close()
	pix, err := ioutil.ReadAll(resp.Body)
	n, err = io.Copy(out, bytes.NewReader(pix))

	// delete temp file

	return

}

func exists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return true, err
}
